package handler

import (
	"context"
	"gitee.com/llqhz/go-micro-user/user/domain/model"
	"gitee.com/llqhz/go-micro-user/user/domain/service"
	pb "gitee.com/llqhz/go-micro-user/user/proto/user"
)

type User struct {
	UserService service.IUserService
}

func (u *User) Register(ctx context.Context, request *pb.UserRegisterRequest, response *pb.UserRegisterResponse) error {
	user := &model.User{
		UserName:     request.UserName,
		FirstName:    request.FirstName,
		HashPassword: request.Pwd,
	}

	if _, err := u.UserService.AddUser(user); err != nil {
		return err
	}
	response.Message = "添加成功"
	return nil
}

func (u *User) Login(ctx context.Context, request *pb.UserLoginRequest, response *pb.UserLoginResponse) error {
	// 校验用户名和密码, 返回结果
	if isOk, err := u.UserService.CheckPwd(request.UserName, request.Pwd); err != nil {
		return err
	} else {
		response.IsSuccess = isOk
	}
	return nil
}

func (u *User) GetUserInfo(ctx context.Context, request *pb.UserInfoRequest, response *pb.UserInfoResponse) error {
	// 查数据, 返回结果
	if user, err := u.UserService.FindUserByName(request.UserName); err != nil {
		return err
	} else {
		SetUserResponse(user, response)
	}
	return nil
}

func SetUserResponse(user *model.User, response *pb.UserInfoResponse) {
	response.UserId = user.ID
	response.UserName = user.UserName
	response.FirstName = user.FirstName
}
